package com.haitaoit.chengquan.module.center.activity.xuqiu;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.center.adapter.xuqiu.MyXuqiuAdapter;
import com.haitaoit.chengquan.module.center.model.MyXuqiuModel;
import com.haitaoit.chengquan.module.home.activity.fabu.SendNeedActivity;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MyXuqiuActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pull_to_refresh_scrollview)
    PullToRefreshScrollView pullrefreshscrollview;
    @ViewInject(R.id.xuqiu_all)
    TextView xuqiu_all;
    @ViewInject(R.id.xuqiu_nooffer)
    TextView xuqiu_nooffer;
    @ViewInject(R.id.xuqiu_already_offer)
    TextView xuqiu_already_offer;
    @ViewInject(R.id.xuqiu_already_pay)
    TextView xuqiu_already_pay;
    @ViewInject(R.id.xuqiu_finish)
    TextView xuqiu_finish;
    @ViewInject(R.id.xuqiu_line1)
    View xuqiu_line1;
    @ViewInject(R.id.xuqiu_line2)
    View xuqiu_line2;
    @ViewInject(R.id.xuqiu_line3)
    View xuqiu_line3;
    @ViewInject(R.id.xuqiu_line4)
    View xuqiu_line4;
    @ViewInject(R.id.xuqiu_line5)
    View xuqiu_line5;
    @ViewInject(R.id.all_count)
    TextView all_count;
    @ViewInject(R.id.no_quotation_count)
    TextView no_quotation_count;
    @ViewInject(R.id.already_offer_count)
    TextView already_offer_count;
    @ViewInject(R.id.have_pay_count)
    TextView have_pay_count;
    @ViewInject(R.id.been_completed_count)
    TextView been_completed_count;

    private LinearLayout null_information_layout;
    private MyListView listView;
    private ScrollView mScrollView;
    private EditText search_et;

    private boolean isFrist = true;
    private int page = 1;
    private String order_type = "all";

    private MyXuqiuAdapter adapter;
    private Dialog dlg;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_my_xuqiu);
        setTitle_V("需求管理");
        setLeftShow(1, R.mipmap.left);
//        setRightShow(0, R.string.send_xuqiu);
        backLeft_V();
        ViewUtils.inject(this);


        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout2, null);
        findViewById(R.id.search_LL).setVisibility(View.VISIBLE);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);
        search_et = (EditText) findViewById(R.id.search_et);
        search_et.setHint("请输入搜索内容...");
        findViewById(R.id.search_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (search_et.getText().toString().equals("")) {
                    ToastUtils.showToast("输入搜索内容！");
                } else {
                    isFrist = true;
                    page = 1;
                    httpGetuser_demand_list();
                }
            }
        });

        pullrefreshscrollview.setPullLoadEnabled(true);
        pullrefreshscrollview.setPullRefreshEnabled(true);
        pullrefreshscrollview.setOnRefreshListener(this);
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pullrefreshscrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new MyXuqiuAdapter(this);
        adapter.setBackCall(backCall);
        listView.setAdapter(adapter);
        httpGetuser_demand_list();
    }

    // 发布成功返回刷新
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == 16 && resultCode == 1) {
//            isFrist = true;
//            page = 1;
//            httpGetuser_demand_list();
//        }
//        super.onActivityResult(requestCode, resultCode, data);
//    }

    @Override
    protected void onResume() {
        isFrist = true;
        page = 1;
        httpGetuser_demand_list();
        super.onResume();
    }
//R.id.right,
    @OnClick({ R.id.xuqiu_all, R.id.xuqiu_nooffer, R.id.xuqiu_already_offer,
            R.id.xuqiu_already_pay, R.id.xuqiu_finish,})
    public void onClick(View v) {
        Intent intent = new Intent();
        String string = search_et.getText().toString();
        switch (v.getId()) {
            case R.id.right:// 发布需求
                intent.setClass(this, SendNeedActivity.class);
//                startActivityForResult(intent, 16);
                startActivity(intent);
                break;
            case R.id.xuqiu_all:// 全部
                setColor();
                xuqiu_all.setTextColor(getResources().getColor(R.color.app_color));
                xuqiu_line1.setVisibility(View.VISIBLE);

                order_type = "all";
                isFrist = true;
                page = 1;
                if (TextUtils.isEmpty(string)){
                    isFrist = true;
                    page = 1;
                    httpGetuser_demand_list();
                }
                httpGetuser_demand_list();
                break;
            case R.id.xuqiu_nooffer:// 未报价
                setColor();
                xuqiu_nooffer.setTextColor(getResources().getColor(R.color.app_color));
                xuqiu_line2.setVisibility(View.VISIBLE);

                order_type = "nooffer";
                isFrist = true;
                page = 1;

                if (TextUtils.isEmpty(string)){
                    isFrist = true;
                    page = 1;
                    httpGetuser_demand_list();
                }
                httpGetuser_demand_list();
                break;
            case R.id.xuqiu_already_offer:// 已报价
                setColor();
                xuqiu_already_offer.setTextColor(getResources().getColor(R.color.app_color));
                xuqiu_line3.setVisibility(View.VISIBLE);

                order_type = "already_offer";
                isFrist = true;
                page = 1;
                if (TextUtils.isEmpty(string)){
                    isFrist = true;
                    page = 1;
                    httpGetuser_demand_list();
                }
                httpGetuser_demand_list();
                break;
            case R.id.xuqiu_already_pay:// 已支付
                setColor();
                xuqiu_already_pay.setTextColor(getResources().getColor(R.color.app_color));
                xuqiu_line4.setVisibility(View.VISIBLE);

                order_type = "already_pay";
                isFrist = true;
                page = 1;
                if (TextUtils.isEmpty(string)){
                    isFrist = true;
                    page = 1;
                    httpGetuser_demand_list();
                }
                httpGetuser_demand_list();
                break;
            case R.id.xuqiu_finish:// 已完成
                setColor();
                xuqiu_finish.setTextColor(getResources().getColor(R.color.app_color));
                xuqiu_line5.setVisibility(View.VISIBLE);

                order_type = "finish";
                isFrist = true;
                page = 1;
                if (TextUtils.isEmpty(string)){
                    isFrist = true;
                    page = 1;
                    httpGetuser_demand_list();
                }
                httpGetuser_demand_list();
                break;
        }
    }

    BackCall backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            final int position = (Integer) obj[0];
            Intent intent = new Intent();
            switch (which) {
                case R.id.xuqiu_itemll:// 详情


                case R.id.select_service:// 选择服务商
                case R.id.look_offer:// 查看报价
                case R.id.to_me_eva:// 服务商对我的评价
//                case R.id.scrollview_listview:
//                    if (adapter.getList().get(position).getOrder_status().equals("1") ||
//                            adapter.getList().get(position).getOrder_status().equals("2")) {
//                        // 没有选择供应商
//                        intent.setClass(MyXuqiuActivity.this, MyXuqiuDetailActivity.class);
//                        intent.putExtra("order_id", adapter.getList().get(position).getId());
//                        startActivity(intent);
//                    } else if (adapter.getList().get(position).getOrder_status().equals("3") ||
//                            adapter.getList().get(position).getOrder_status().equals("4")) {
                    intent.setClass(MyXuqiuActivity.this, MyXuqiuEndDetailActivity.class);
                    intent.putExtra("order_id", adapter.getList().get(position).getId());
                    startActivity(intent);
//                    }
                    break;
                case R.id.cancel_xuqiu:// 取消需求
                    dlg = DialogUtil.showInfoDialog1(MyXuqiuActivity.this, "提示",
                            "您确定要取消该需求订单吗？", "确定取消", "再想想", new BackCall() {
                                public void deal(int which, Object... obj) {
                                    switch (which) {
                                        case R.id.confirm:// 确定
                                            httpGetcancel_order(adapter.getList().get(position).getDemand_number());
                                            break;
                                    }
                                    super.deal(which);
                                }
                            });
                    dlg.setCanceledOnTouchOutside(true);
                    dlg.show();
                    break;
                case R.id.finish:// 服务完成
                    dlg = DialogUtil.showInfoDialog1(MyXuqiuActivity.this, "提示",
                            "您确定该需求服务已完成吗？", "确定", "还没有", new BackCall() {
                                public void deal(int which, Object... obj) {
                                    switch (which) {
                                        case R.id.confirm:// 确定
                                            httpGetdemand_complete_order(adapter.getList().get(position).getOrder_no());
                                            break;
                                    }
                                    super.deal(which);
                                }
                            });
                    dlg.setCanceledOnTouchOutside(true);
                    dlg.show();
                    break;
                case R.id.go_eva:// 评价服务商
                    intent.setClass(MyXuqiuActivity.this, XuqiuEvaluateActivity.class);
                    intent.putExtra("demand_id", adapter.getList().get(position).getId());
                    intent.putExtra("type", "1");
                    intent.putExtra("circleimage_uri", adapter.getList().get(position).getTitle_img());
                    startActivity(intent);
                    break;
                case R.id.detele_xuqiu:// 删除订单
                    dlg = DialogUtil.showInfoDialog1(MyXuqiuActivity.this, "提示",
                            "您确定要删除该需求订单吗？", "确定", "取消", new BackCall() {
                                public void deal(int which, Object... obj) {
                                    switch (which) {
                                        case R.id.confirm:// 确定
                                            httpGetdel_order(adapter.getList().get(position).getDemand_number());
                                            break;
                                    }
                                    super.deal(which);
                                }
                            });
                    dlg.setCanceledOnTouchOutside(true);
                    dlg.show();
                    break;
            }
            super.deal(which, obj);
        }
    };

    // 列表
    private void httpGetuser_demand_list() {
        int status = 0;// 分类0全部1未报价2已报价3已支付4已完成
        if ("all".equals(order_type)) {
            status = 0;
        } else if ("nooffer".equals(order_type)) {
            status = 1;
        } else if ("already_offer".equals(order_type)) {
            status = 2;
        } else if ("already_pay".equals(order_type)) {
            status = 3;
        } else if ("finish".equals(order_type)) {
            status = 4;
        }

        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("status", status + ""));
        list.add(new NameValuePairSign("name", search_et.getText().toString()));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("status", status + "");
        params.addQueryStringParameter("name", search_et.getText().toString());
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);
        showProgrees("");
        HttpUtilsSingle.doGet(this, false, Constant.Getuser_demand_list, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<MyXuqiuModel> new_list = new ArrayList<MyXuqiuModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            if (new_list!=null){
                                new_list.clear();
                            }
                            hideProgree();
                            break;
                        case 0:// 成功
                            JSONObject js = new JSONObject(Response);
                            all_count.setText(js.getString("all_count"));
                            no_quotation_count.setText(js.getString("no_quotation_count"));
                            already_offer_count.setText(js.getString("already_offer_count"));
                            have_pay_count.setText(js.getString("have_pay_count"));
                            been_completed_count.setText(js.getString("been_completed_count"));

                            if (all_count.getText().toString().equals("0")) {
                                all_count.setVisibility(View.GONE);
                            } else {
                                all_count.setVisibility(View.VISIBLE);
                            }
                            if (no_quotation_count.getText().toString().equals("0")) {
                                no_quotation_count.setVisibility(View.GONE);
                            } else {
                                no_quotation_count.setVisibility(View.VISIBLE);
                            }
                            if (already_offer_count.getText().toString().equals("0")) {
                                already_offer_count.setVisibility(View.GONE);
                            } else {
                                already_offer_count.setVisibility(View.VISIBLE);
                            }
                            if (have_pay_count.getText().toString().equals("0")) {
                                have_pay_count.setVisibility(View.GONE);
                            } else {
                                have_pay_count.setVisibility(View.VISIBLE);
                            }
                            if (been_completed_count.getText().toString().equals("0")) {
                                been_completed_count.setVisibility(View.GONE);
                            } else {
                                been_completed_count.setVisibility(View.VISIBLE);
                            }

                            new_list = gson.fromJson(js.getString("list_dy"),
                                    new TypeToken<List<MyXuqiuModel>>() {
                                    }.getType());
                            hideProgree();
                            break;
                        case 2:// 暂无内容
                            pullrefreshscrollview.onPullDownRefreshComplete();
                            pullrefreshscrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<MyXuqiuModel>();
                            hideProgree();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pullrefreshscrollview.onPullDownRefreshComplete();
                    } else {
                        List<MyXuqiuModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pullrefreshscrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    hideProgree();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
                hideProgree();
            }
        });
    }

    // 需求服务完成订单
    private void httpGetdemand_complete_order(String order_no) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getdemand_complete_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            isFrist = true;
                            page = 1;
                            httpGetuser_demand_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 取消订单
    private void httpGetcancel_order(String order_no) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getcancel_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            isFrist = true;
                            page = 1;
                            httpGetuser_demand_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    // 删除订单
    private void httpGetdel_order(String order_no) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        list.add(new NameValuePairSign("order_no", order_no));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("order_no", order_no);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, Constant.Getdel_order, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            return;
                        case 0:// 成功
                            ToastUtils.showToast(Errmsg);
                            isFrist = true;
                            page = 1;
                            httpGetuser_demand_list();
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    public void setColor() {
        xuqiu_all.setTextColor(getResources().getColor(R.color.black_text));
        xuqiu_nooffer.setTextColor(getResources().getColor(R.color.black_text));
        xuqiu_already_offer.setTextColor(getResources().getColor(R.color.black_text));
        xuqiu_already_pay.setTextColor(getResources().getColor(R.color.black_text));
        xuqiu_finish.setTextColor(getResources().getColor(R.color.black_text));

        xuqiu_line1.setVisibility(View.INVISIBLE);
        xuqiu_line2.setVisibility(View.INVISIBLE);
        xuqiu_line3.setVisibility(View.INVISIBLE);
        xuqiu_line4.setVisibility(View.INVISIBLE);
        xuqiu_line5.setVisibility(View.INVISIBLE);
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<MyXuqiuModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        httpGetuser_demand_list();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pullrefreshscrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        httpGetuser_demand_list();
    }
}
